package com.asman.worker.utils

import android.app.DownloadManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.core.content.ContextCompat.getSystemService
import androidx.core.net.toUri
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent
import com.asman.base.lib.utils.PermissionUtils
import showToast


/**
 * @author ybk
 * @date :2019-09-29 10:13
 * @desc:下载文件到指定的文件夹
 */
class ImageDownloadUtils(val activity: FragmentActivity) {

    companion object {
        fun newInstance(activity: FragmentActivity) =
            ImageDownloadUtils(activity)
    }

    fun startDownload(
        downloadUrl: String?,
        folderName: String,
        fileName: String,
        successCallBack: (() -> Unit)? = null
    ) {
        if (downloadUrl.isNullOrEmpty()) {
            showToast("下载地址为空")
            return
        }
        PermissionUtils.requestReadWriteSDCard(activity,
            object : PermissionUtils.OnPermissionListener() {
                override fun success() {
                    val downloadManager: DownloadManager? =
                        getSystemService(activity, DownloadManager::class.java)
                    val request = DownloadManager.Request(downloadUrl.toUri())
//                    val apkName = "牛牛搭新家工地_${System.currentTimeMillis()}.jpg"
                    request.setDestinationInExternalPublicDir(folderName, fileName)
                    //start 一些非必要的设置
                    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE or DownloadManager.Request.NETWORK_WIFI)
                    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
                    request.setVisibleInDownloadsUi(true)
                    request.setTitle(fileName)
                    //end 一些非必要的设置
                    downloadManager?.enqueue(request)
                    val completeReceiver = AppDownloadCompleteReceiver(successCallBack)
                    activity.registerReceiver(
                        completeReceiver, IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)
                    )
                    (activity as LifecycleOwner).lifecycle.addObserver(object :
                        LifecycleObserver {
                        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
                        fun onDestory() {
                            //取消注册
                            activity.unregisterReceiver(completeReceiver)
                        }
                    })
                }
            })
    }

    inner class AppDownloadCompleteReceiver(
        private val successCallBack: (() -> Unit)? = null
    ) :
        BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            successCallBack?.invoke()
        }
    }
}